package com.gupao.jly521;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.*;

/**
 * @date 2018/8/21  14:23
 * @author Jly
 */
@Mojo(name = "versionControl", defaultPhase = LifecyclePhase.PACKAGE)
public class VersionControlMojo extends AbstractMojo {

    @Parameter
    private String webappPath;

    @Parameter
    private String version;

    @Parameter(defaultValue = ".html")
    private String endStr;

    @Parameter(defaultValue = ".js,.css")
    private String dealFile;

    public void execute() throws MojoExecutionException, MojoFailureException {
        System.out.println("gupaoedu plugin  !!!" + webappPath);
        System.out.println("gupaoedu plugin  !!!" + endStr);
        File file = new File(webappPath);
        visitFiles(file);
    }

    /**
     *  递归遍历所有文件
     * @date 2018/8/21 12:56
     * @author Jly
     * @param [file]
     * @return void
     */
    private void visitFiles(File file){
        File[] fs = file.listFiles();	//遍历path下的文件和目录，放在File数组中
        for(File f : fs){					//遍历File[]数组
            if(f.isFile())	{      //若非目录(即文件)，则打印
                if(f.getName().endsWith(endStr)){
                    modifyFile(f);
                }
            }else if(f.isDirectory()){
                visitFiles(f);
            }
        }
    }

    /**
     *  生成版本号
     * @date 2018/8/21 14:15
     * @author Jly
     * @param []
     * @return java.lang.String
     */
    private String generateVersion(){
        if (version!=null){
            return version;
        }
        String resStr = System.currentTimeMillis()+"";
        return resStr;
    }

    /**
     *  处理特殊字段
     * @date 2018/8/21 14:17
     * @author Jly
     * @param [line]
     * @return java.lang.String
     */
    private String dealWithLineStr(String line){
        String[] endArray = dealFile.split(",");
        for (String str : endArray) {
            if(line.contains(str)) {
                line = line.replace(".js", ".js?v="+generateVersion());
            }
        }
        return line;
    }

    /**
     *  替换文件对应内容
     * @date 2018/8/21 14:25
     * @author Jly
     * @param [file]
     * @return void
     */
    private void modifyFile(File file){
        File fileNew = new File(file.getAbsolutePath()+".new");
        String filePath = file.getAbsolutePath();
        try{
            String line="";
            BufferedReader in=new BufferedReader(new FileReader(file));
            BufferedWriter out=new BufferedWriter(new FileWriter(fileNew));
            line=in.readLine();
            while (line!=null){
                out.write(dealWithLineStr(line));
                out.newLine();
                line=in.readLine();
            }
            in.close();
            out.close();
        } catch (IOException e){
            e.printStackTrace();
        }
        file.delete();
        File fileBack = new File(filePath);
        fileNew.renameTo(fileBack);
    }

    @Deprecated
    public static void readFile(File file){
        try{
            String line="";
            BufferedReader in=new BufferedReader(new FileReader(file));
            line=in.readLine();
            while (line!=null)
            {
                System.out.println(line);
                line=in.readLine();
            }
            in.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    @Deprecated
    public static void writeFile(File flie){
         try{
             BufferedWriter out=new BufferedWriter(new FileWriter(flie));
             out.write("Hello Kuka:");
             out.newLine();  //注意\n不一定在各种计算机上都能产生换行的效果
             out.write("  My name is coolszy!\n");
             out.write("  I like you and miss you。");
             out.close();
         } catch (IOException e)
         {
             e.printStackTrace();
         }
     }

    @Deprecated
    public static void main(String[] args) throws FileNotFoundException {
        VersionControlMojo obj = new VersionControlMojo();
        obj.modifyFile(new File("D:\\0_jly\\20180821\\2.html"));
    }

    @Deprecated
    private boolean modifyFileContent(File file){
        RandomAccessFile raf = null;
        try {
            raf = new RandomAccessFile(file, "rw");
            String line = null;
            long lastPoint = 0; //记住上一次的偏移量
            while ((line = raf.readLine()) != null) {
                final long ponit = raf.getFilePointer();
                if(line.contains(".js")){
                    System.out.println(line);
                    String str=line.replace(".js", ".js?v=1.4.1")+"\n";
                    System.out.println(str);
                    raf.seek(lastPoint);
                    raf.write(str.getBytes());
                }
                lastPoint = ponit;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                raf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return true;
    }
}
